package com.example.highclasscomponent;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleAdapterActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    //下拉列表的图标数组
    public static final int[] iconArray={
            R.drawable.shuixing,R.drawable.jinxing,R.drawable.diqiu,
            R.drawable.huoxing,R.drawable.muxing,R.drawable.tuxing
    };
    //定义下拉列表需要显示的行星名称数组
    public static final String[] starArray={"水星","金星","地球","火星","木星","土星 "};



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_adapter);
        Spinner spn = findViewById(R.id.spn_simpleAdapter);
        //声明一个映射对象的列表，用于保存行星的图标与名称配对信息
        List<Map<String,Object>> list=new ArrayList<>();
        for (int i = 0; i < iconArray.length; i++) {
            Map<String,Object>item=new HashMap<>();
            item.put("icon",iconArray[i]);
            item.put("name",starArray[i]);
            list.add(item);
        }
        SimpleAdapter startAdapter=new SimpleAdapter(this,list,
                R.layout.item_simple,
                new String[]{"icon","name"},
                new int[]{R.id.iv_plant,R.id.tv_name});
        spn.setAdapter(startAdapter);
        spn.setSelection(0);
        spn.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(this, "选择了"+starArray[position], Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
